/* eslint-disable */
import { isFormData } from '@/utils/helper'
import errorHandle from './errorHandle'
import { getUrlParam,translate } from '@/utils/helper'
import { Toast } from 'vant'
import '@/qing/qing.js'
import router from '@/router'
import store from '@/store'
/**
 * @desc NO_ERROR_HANDLER
 * @param { method: string, code: number } NO_ERROR_HANDLER { http method name， http res code} 
 */
const NO_ERROR_HANDLER = ['/message/getHmacSHA1']

/**
 *
 * @param res 请求返回实体
 * @returns {boolean} 是否需要通用error处理
 */


function isNotErrorhandle (res) {
  const method = res.config.url
  const code = res.data.error_code
  return NO_ERROR_HANDLER.some((v) => {
    return method.indexOf(v.method) !== -1 && (!code || v.code.includes(code))
  })
}

/*
* 根据请求的类型获取对应的数据字段
*/
function getRqDataKey (method) {
  if (['post', 'put'].includes(method)) {
    return 'data'
  }
  if (['get', 'delete'].includes(method)) {
    return 'params'
  }
  return ''
}

// 默认请求的拦截器
const reqestHandle = (config) => {
  const method = config.method.toLowerCase()
  const paramKey = getRqDataKey(method)
  const params = config[paramKey]

  if (isFormData(params)) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    return config
  }
  qing.call('getNetworkType', {
    success:function(res){
      const $lang1 = translate()
      console.warn(res.data.network_type,"成功");
      // Toast.fail($lang1.errorNetwork)
      if(res.data.network_type == 'fail'){
        Toast.fail($lang1.errorNetwork)
        console.warn('断网了');
      }
    },
    error:function(e){
      console.warn(e,"失败");
    }
  })
  // const ticket = getUrlParam('ticket')
  const ticket = localStorage.getItem('ticket') || getUrlParam('ticket')
  const appId = getUrlParam('appid') || getUrlParam('client_id') || getUrlParam('appId')
  const index = config.url.indexOf('?')
  // 所有请求加入ticket 和 appid 参数 （加到路径上）
  if (appId && ticket) {
    config.url += `${index === -1 ? '?':'&'}ticket=${ticket}&appId=${appId}`
  }else{
    console.error("当前ticket",ticket,"appid",appId,location.href);
  }

  // config.url += `${index === -1 ? '?':'&'}isNavHidden=true` //隐藏顶部应用内tab

  // console.warn(ticket,"::::");
  if (Array.isArray(params)) {
    config[paramKey] = params
  }
  return config
}

// 默认请求的错误拦截器
const errorRqHandle = (error) => Promise.reject(error)

// 默认响应的拦截器
const responseHandle = (res) => {
    if (res.data.errorCode === "403") {
        // console.error(res)
        const data = res?.data?.data
        window.location.replace(data)
        return
    }
    if (res.config.url.indexOf("/message/getHmacSHA1") !== -1  || res.config.url.indexOf("/message/getUrl") !== -1  ) {
        return Promise.resolve(res)
    }
    // 测试使用
    if (res.config.url ===  "/peace") {
        return Promise.resolve(res)
    }
    if (!res.data.success && !isNotErrorhandle(res)) {
        errorHandle(res)
        return Promise.reject(res)
    }

    return res
}

// 默认响应的错误拦截器
const errorResandle = (error) => {
  return errorHandle(error.response, error)
}

export default {
  request: [reqestHandle, errorRqHandle],
  response: [responseHandle, errorResandle]
}
